package com.snda.dsync;

import java.io.File;
import java.net.MalformedURLException;
import java.net.URL;

import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.CommandLineParser;
import org.apache.commons.cli.HelpFormatter;
import org.apache.commons.cli.Option;
import org.apache.commons.cli.Options;
import org.apache.commons.cli.ParseException;
import org.apache.commons.cli.PosixParser;
import org.apache.commons.vfs.FileSystemException;
import org.apache.hadoop.fs.FsUrlStreamHandlerFactory;

public class Dsync {

	private static String FROM = "from";
	private static String TO = "to";
	private static String DELETE = "delete";
	private static String IGNORE = "ignore";
	private static String HELP = "help";
	private static String PATH = "path";


	public static void main(String[] args) throws ParseException,
			MalformedURLException, FileSystemException {
		URL.setURLStreamHandlerFactory(new FsUrlStreamHandlerFactory());

		CommandLineParser parser = new PosixParser();
		Options options = new Options();
		options.addOption(HELP, false, "print help message");
		options.addOption(FROM, true, FROM);
		options.addOption(TO, true, TO);
		options.addOption(DELETE, false, DELETE);
		options.addOption(PATH, true, PATH);
		Option ignoreOption = new Option(IGNORE, IGNORE);
		ignoreOption.setArgs(Option.UNLIMITED_VALUES);
		options.addOption(ignoreOption);

		CommandLine cl = parser.parse(options, args);
		if (cl.hasOption(HELP)) {
			HelpFormatter formatter = new HelpFormatter();
			formatter.printHelp("ant", options);
			return;
		}
		if (!cl.hasOption(FROM) || !cl.hasOption(TO)) {
			System.err.println("there need from or to");
			return;
		}
		URL from;
		try {
			from = new URL(cl.getOptionValue(FROM));
		} catch (MalformedURLException e) {
			from = new File(cl.getOptionValue(FROM)).toURI().toURL();
		}
		URL to;
		try {
			to = new URL(cl.getOptionValue(TO));
		} catch (MalformedURLException e) {
			to = new File(cl.getOptionValue(TO)).toURI().toURL();
		}

		VFSSyncer dsync = new VFSSyncer(from, to);
		if (cl.hasOption(DELETE)) {
			dsync.delete = true;
		}if (cl.hasOption(PATH)) {
			dsync.path = cl.getOptionValue(PATH);
		}
		if (cl.hasOption(IGNORE)) {
			dsync.addIgnore(cl.getOptionValues(IGNORE));
		}
		dsync.run();
	}
}
